<template>
  <div class="background-container">
    <!-- 搜索部分 -->
    <div class="search-container">
      <el-autocomplete
          style="width: 90%"
          popper-class="my-autocomplete"
          v-model="message"
          :fetch-suggestions="querySearch"
          placeholder="请输入消息"
          @select="handleSelect"
      >
        <!-- 自定义后缀图标 -->
        <template #suffix>
          <el-icon @click="handleIconClick" style="cursor: pointer;">
            <Edit />
          </el-icon>
        </template>

        <!-- 自定义下拉建议项 -->
        <template #default="{ item }">
          <div class="name">{{ item.value }}</div>
        </template>
      </el-autocomplete>

      <el-button type="primary" @click="analyzeMessage" style="margin-left: 10px;">
        分析消息
      </el-button>
    </div>

    <!-- 显示分析结果 -->
    <div class="result-container">
      <!-- 空状态 -->
      <el-empty v-if="!loading && !analysisResult" description="请输入消息并点击分析按钮" />

      <!-- 加载动画 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" :size="30">
          <Loading />
        </el-icon>
        <span style="margin-left: 10px;">数据加载中...</span>
      </div>

      <!-- 图表 -->
      <div v-if="analysisResult" id="chart-container" style="width: 100%; height: 400px;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { analyzeMessage } from '../Api/api.js';
import { Edit, Loading } from '@element-plus/icons-vue';

export default {
  components: {
    Edit,
    Loading,
  },
  data() {
    return {
      message: '',
      analysisResult: null,
      loading: false,
      restaurants: [
        {value: '你'},
        {value: '我'},
        {value: '人'},
        {value: '爱'},
        {value: '想'},
      ],
      chart: null,
      currentIndex: -1 // 用于高亮切换
    };
  },
  methods: {
    querySearch(queryString, cb) {
      const results = queryString
          ? this.restaurants.filter(this.createFilter(queryString))
          : this.restaurants;
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) =>
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
    },
    handleSelect(item) {
      console.log(item);
    },
    handleIconClick() {
      console.log('编辑图标被点击');
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(document.getElementById('chart-container'));

      const option = {
        title: {
          text: '消息时间段分布分析结果',
          left: 'center'
        },
        aria: {
          enabled: true,
          decal: {
            show: true
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.analysisResult.map(item => item.timePeriod) // 使用时间周期作为图例
        },
        series: [
          {
            name: '数量',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.analysisResult.map(item => ({
              value: item.msgCnt,
              name: item.timePeriod
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.chart.setOption(option);

      // 自动切换高亮效果
      setInterval(() => {
        const dataLen = option.series[0].data.length;
        // 取消之前高亮的图形
        this.chart.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          dataIndex: this.currentIndex
        });
        this.currentIndex = (this.currentIndex + 1) % dataLen;
        // 高亮当前图形
        this.chart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: this.currentIndex
        });
        // 显示 tooltip
        this.chart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: this.currentIndex
        });
      }, 1000);

      // 响应式调整
      window.addEventListener('resize', () => {
        this.chart.resize();
      });
    },
    async analyzeMessage() {
      if (!this.message) {
        alert('请输入消息');
        return;
      }

      this.loading = true; // 开始加载

      try {
        const response = await analyzeMessage('api/message/analyze', {message: this.message});
        this.analysisResult = response.data;
        console.log('分析结果:', response);

        // 初始化图表
        this.$nextTick(() => {
          this.initChart();
          this.loading = false; // 结束加载
        });
      } catch (error) {
        console.error('分析失败:', error);
        if (error.response) {
          console.error('后端响应状态码:', error.response.status);
          console.error('后端响应数据:', error.response.data);
        }
        this.loading = false; // 结束加载
        alert('分析失败');
      }
    },
  },
  beforeUnmount() {
    // 组件销毁时销毁图表实例
    if (this.chart) {
      this.chart.dispose();
    }
  }
};
</script>

<style scoped>

.search-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  margin-bottom: 20px;
}

.result-container {
  margin-top: 20px;
  min-height: 400px; /* 保持容器高度一致 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 20px;
}

.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}
</style>